﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Hotnet.Entity;
using System.Threading;
using System.Data.Common;
using System.Data;

namespace Hotnet.Dal.BaseRepository
{
	public static class DBDataContext
	{
		private static Dictionary<int, HotnetDBDataContext> DataContextCached = new Dictionary<int, HotnetDBDataContext>();
		public static HotnetDBDataContext GetDataContext()
		{
			HotnetDBDataContext dataContext = null;
			string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["HotnetConnectionString"].ConnectionString;
			DataContextCached.TryGetValue(Thread.CurrentThread.ManagedThreadId, out dataContext);
			if (dataContext == null)
			{
				dataContext = new HotnetDBDataContext(connectionString);
				DataContextCached[Thread.CurrentThread.ManagedThreadId] = dataContext;
			}

			return dataContext;
		}

		public static DbTransaction GetTransaction()
		{
			HotnetDBDataContext dataContext = GetDataContext();
			if (dataContext.Transaction == null)
			{
				if (dataContext.Connection != null && dataContext.Connection.State == ConnectionState.Closed)
				{
					//打开连接
					dataContext.Connection.Open();
				}

				dataContext.Transaction = dataContext.Connection.BeginTransaction();
			}
			return dataContext.Transaction;
		}

		public static bool HasDataContext(int threadId)
		{
			return DataContextCached.ContainsKey(threadId);
		}
	}
}
